﻿using SGA.Classes;
using SGA.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SGA.Support
{
    public partial class EditSupporter : System.Web.UI.Page
    {
        /// <summary>
        /// constantes para a o tipo de cobrança
        /// </summary>
        private const int K_FIRST_COLLECTION = 1;
        private const int K_AMENDMENT_NONE = 1;         //1	<nenhum>
        private const int K_AMENDMENT_CHG_AUTH = 2;     //2	Alteração de autorização bancária
        private const int K_AMENDMENT_CHG_ACC = 3;      //3	Alteração de conta bancária (dentro do mesmo banco)
        private const int K_AMENDMENT_CHG_BNK = 4;      //4	Alteração de Banco
        private const int K_AMENDMENT_CHG_BNK_AUTH = 5; //5	Alteração de Banco e autorização bancária
        private const int K_DONATION_SITUATION_DM = 3;  //3 DM - Donativo Mensal

        /// <summary>
        /// constantes para os separadores de ajaxToolkit:TabContainer
        /// </summary>
        private const int TAB_SUPPORTER = 0;
        private const int TAB_ASSOCIATE = 1;
        private const int TAB_MAILING = 2;
        private const int TAB_MATERIALORDERS = 3;
        private const int TAB_RECEIPTS = 4;
        private const int TAB_INVOICES = 5;

        private decimal sumReceipts = 0;
        private int countReceipts = 0;

        private decimal sumInvoices = 0;
        private int countInvoices = 0;

        private int idSupporter;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string stringId = Request.QueryString["Id"];
                idSupporter = Convert.ToInt32(stringId);
                if (idSupporter > 0)
                {
                    SaveButton.Visible = false;
                    UpdateButton.Visible = true;
                    //FillForm(IdSupporter);
                    BindData();
                    HiddenFieldIdSupportersGlobal.Value = idSupporter.ToString();
                    string supporterName = GetSupporterName();
                    TabAssociado_SupporterName.Text = idSupporter.ToString() + " - " + supporterName;
                }

            }
        }

        private String GetSupporterName()
        {
            string name;
            using (var bd = new MailingEntities())
            {
                SGA.Model.Supporters query = (from supporter in bd.Supporters
                                              where supporter.Id == idSupporter
                                              select supporter).SingleOrDefault();

                name = query.Designation;
            }
            return name;
        }

        private void BindData()
        {
            //Bind formview by supporter id
            FVSupporters.DataSourceID = "EDSSupporters";
            EDSSupporters.EnableUpdate = true;
            EDSSupporters.EnableInsert = false;
            EDSSupporters.EnableDelete = false;
            EDSSupporters.AutoGenerateWhereClause = true;
            Parameter filterNumberSupporters = new Parameter("Id", System.TypeCode.Int32, idSupporter.ToString());
            EDSSupporters.WhereParameters.Clear();
            EDSSupporters.WhereParameters.Add(filterNumberSupporters);
            FVSupporters.DataBind();

            //Bind listview supporter by supporter IdSupporter
            LVSupporterContacts.DataSourceID = "EDSupporterContacts";
            EDSupporterContacts.EnableUpdate = true;
            EDSupporterContacts.EnableInsert = true;
            EDSupporterContacts.EnableDelete = true;
            EDSupporterContacts.AutoGenerateWhereClause = true;
            Parameter filterNumber = new Parameter("IdSupporters", System.TypeCode.Int32, idSupporter.ToString());
            EDSupporterContacts.WhereParameters.Clear();
            EDSupporterContacts.WhereParameters.Add(filterNumber);
            LVSupporterContacts.DataBind();

            FVAssociates.DataSourceID = "EDSAssociates";
            EDSAssociates.EnableUpdate = true;
            EDSAssociates.EnableInsert = false;
            EDSAssociates.EnableDelete = false;
            EDSAssociates.AutoGenerateWhereClause = true;
            EDSAssociates.WhereParameters.Clear();
            EDSAssociates.WhereParameters.Add(filterNumber);

            //Bind listview mailing by supporter id
            LVMailing.DataSourceID = "EDSExpeditions";
            EDSExpeditions.EnableUpdate = true;
            EDSExpeditions.EnableInsert = false;
            EDSExpeditions.EnableDelete = false;
            EDSExpeditions.AutoGenerateWhereClause = true;
            EDSExpeditions.WhereParameters.Clear();
            EDSExpeditions.WhereParameters.Add(filterNumber);
            LVMailing.DataBind();

            //Bind listview order by supporter id
            LVOrder.DataSourceID = "EDSMaterialOrders";
            EDSMaterialOrders.EnableUpdate = false;
            EDSMaterialOrders.EnableInsert = false;
            EDSMaterialOrders.EnableDelete = false;
            EDSMaterialOrders.AutoGenerateWhereClause = true;
            EDSMaterialOrders.WhereParameters.Clear();
            EDSMaterialOrders.WhereParameters.Add(filterNumber);
            LVOrder.DataBind();

            LVInvoice.DataSourceID = "EDSInvoices";
            EDSInvoices.EnableUpdate = false;
            EDSInvoices.EnableInsert = false;
            EDSInvoices.EnableDelete = false;
            string sqlInvoices = "select invoices.designation, sum(invoicedetails.unityprice*invoicedetails.quantity) as soma from invoicedetails left join invoices on invoicedetails.idinvoices = invoices.id where invoices.idsupporters = " + idSupporter + " group by invoices.designation";
            EDSInvoices.CommandText = sqlInvoices;
            LVInvoice.DataBind();

            LVReceipts.DataSourceID = "EDSReceipts";
            EDSReceipts.EnableUpdate = false;
            EDSReceipts.EnableInsert = false;
            EDSReceipts.EnableDelete = false;
            string sqlReceipts = "select Receipts.designation, sum(ReceiptDetails.unityprice) as soma from ReceiptDetails left join Receipts on ReceiptDetails.IdReceipts = Receipts.id where Receipts.idsupporters = " + idSupporter + " group by Receipts.designation";
            EDSReceipts.CommandText = sqlReceipts;
            LVReceipts.DataBind();

            FillSuspensionFields();

        }

        /// <summary>
        /// preenche os campos relativos à suspensão
        /// </summary>
        public void FillSuspensionFields()
        {
            using (MailingEntities bd = new MailingEntities())
            {
                //adquire o maior id para o associado
                int maxId = (from susp in bd.AssociateSuspensions
                             where susp.IdSupporters == idSupporter
                             select susp.Id).DefaultIfEmpty(0).Max();

                if (maxId != 0)
                {
                    AssociateSuspensions qrySusp = (from susp in bd.AssociateSuspensions
                                                    where susp.Id == maxId
                                                    select susp).SingleOrDefault();
                    TextBox txt;
                    txt = FVAssociates.FindControl("ResumingDateTbox") as TextBox;
                    txt.Text = Generic.Instance.formatDateToString(qrySusp.ResumingDate);

                    txt = FVAssociates.FindControl("SuspensionDateTbox") as TextBox;
                    txt.Text = Generic.Instance.formatDateToString(qrySusp.SuspensionDate);

                    DropDownList Ddl;
                    Ddl = FVAssociates.FindControl("SuspensionContatTypeDdl") as DropDownList;
                    Ddl.SelectedValue = qrySusp.IdSuspensionContactTypes.ToString();

                    Ddl = FVAssociates.FindControl("ReasonSuspDdl") as DropDownList;
                    Ddl.SelectedValue = qrySusp.IdReasonForSuspension.ToString();
                }
            }
        }

        /// <summary>
        /// preenche a TextBox com a sequencia numérica da autorização que deve ser mandada ao Banco
        /// </summary>
        /// <param name="sequence"></param>
        /// <returns></returns>
        public string SequenceNumber(string sequence)
        {
            return Generic.Instance.getResumenSequence(idSupporter, sequence);
        }


        public string LastName(string fullname)
        {
            string lastName = "";
            string[] names = fullname.Split(' ');
            if (names.Length >= 2)
            {
                lastName = names[names.Length - 1];
            }
            return lastName;
        }

        private string SplitFullName(string fullname)
        {
            string shortName = "";
            string[] names = fullname.Split(' ');
            if (names.Length >= 2)
            {
                shortName = names[0] + " " + names[names.Length - 1];
            }
            else
            {
                shortName = names[0];
            }

            return shortName;
        }

        protected void LVSupporterContacts_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            //BindData(Convert.ToInt32(HiddenFieldIdSupportersGlobal.Value));
            BindData();
        }

        protected void LVSupporterContacts_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            e.Values["IdSupporters"] = Convert.ToInt32(HiddenFieldIdSupportersGlobal.Value);
        }

        /// <summary>
        /// Actualiza a base de dados com as alterações feitas
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateButton_Click(object sender, EventArgs e)
        {
            //FVSupporters.UpdateItem(true);

            //using (var bd = new MailingEntities()) {
            //    SGA.Model.Supporters querySupporter = (from supporter in bd.Supporters where supporter.Id == Convert.ToInt32(IdSupportersTextBox.Text) select supporter).SingleOrDefault();
            //    querySupporter.Designation = NameTextBox.Text;
            //    bd.SaveChanges();
            //}

            try
            {
                switch (SupporterTabContainer.ActiveTabIndex)
                {
                    case TAB_SUPPORTER:
                        FVSupporters.UpdateItem(true);
                        break;
                    case TAB_ASSOCIATE:
                        FVAssociates.UpdateItem(true);
                        break;
                    case TAB_MAILING:

                        break;
                    case TAB_MATERIALORDERS:

                        break;
                    case TAB_RECEIPTS:

                        break;
                    case TAB_INVOICES:

                        break;
                    default:
                        throw new Exception("Opção desconhecida! Informe o programador.");
                }
            }
            catch (Exception ex)
            {
                //Label lbl = (Label)FVAssociates.FindControl("NotificationLabel");
                //lbl.Visible = true;
                //lbl.Text = ex.Message.ToString();
                NotificationLabel.Visible = true;
                NotificationLabel.Text = ex.Message.ToString();
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.itemupdating(v=vs.110).aspx
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FVSupporters_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            String keyValue = e.Keys["Id"].ToString();
            //BindData(Convert.ToInt32(HiddenFieldIdSupportersGlobal.Value));
            BindData();
        }

        protected void LabelReceiptValue_DataBinding(object sender, EventArgs e)
        {
            decimal sumRec = Convert.ToDecimal(Eval("Soma"));
            sumReceipts += sumRec;
            countReceipts += 1;
        }

        protected void LVReceipts_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Label sumReceiptLabel = (Label)LVReceipts.FindControl("LabelTotalSumReceipt");
            Label countReceiptLabel = (Label)LVReceipts.FindControl("LabelTotalCountReceipt");

            sumReceiptLabel.Text = String.Format(sumReceipts.ToString(), "{0:C}");
            countReceiptLabel.Text = "(" + countReceipts.ToString() + ")";
        }

        protected void LabelInvoiceValue_DataBinding(object sender, EventArgs e)
        {
            decimal sumInv = Convert.ToDecimal(Eval("Soma"));
            sumInvoices += sumInv;
            countInvoices += 1;
        }

        protected void LVInvoice_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Label sumInvoiceLabel = (Label)LVInvoice.FindControl("LabelTotalSumInvoice");
            Label countInvoiceLabel = (Label)LVInvoice.FindControl("LabelTotalCountInvoice");

            sumInvoiceLabel.Text = String.Format(sumInvoices.ToString(), "{0:C}");
            countInvoiceLabel.Text = "(" + countInvoices.ToString() + ")";
        }

        protected void BackButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("BrowseSupporter.aspx");
        }

        protected void teste(object sender, EventArgs e)
        {
            Console.WriteLine("Teste");
        }

        protected void LVMailing_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                Console.WriteLine("Ola");
            }
        }

        //protected void LVMailing_ItemEditing(object sender, ListViewEditEventArgs e)
        //{
        //    Page.ClientScript.RegisterStartupScript(this.GetType(), "CallChangeTab", "changeTab(2)", true);
        //}


        private void ChangeAssociateButtonsVisibility(bool value)
        {
            CheckIBANBtn.Visible = value;
            ReatamentoBtn.Visible = value;
        }

        protected void SupporterTabContainer_ActiveTabChanged(object sender, EventArgs e)
        {
            try
            {
                NotificationLabel.Visible = false;

                switch (SupporterTabContainer.ActiveTabIndex)
                {
                    case TAB_SUPPORTER:
                        ChangeAssociateButtonsVisibility(false);
                        break;
                    case TAB_ASSOCIATE:
                        ChangeAssociateButtonsVisibility(true);
                        //SupporterTabContainer.Tabs[TAB_MAILING].Visible = true;
                        break;
                    case TAB_MAILING:

                        break;
                    case TAB_MATERIALORDERS:

                        break;
                    case TAB_RECEIPTS:

                        break;
                    case TAB_INVOICES:

                        break;
                    default:
                        throw new Exception("Opção desconhecida! Informe o programador.");
                }
            }
            catch (Exception ex)
            {
                //Label lbl = (Label)FVAssociates.FindControl("NotificationLabel");
                //lbl.Visible = true;
                //lbl.Text = ex.Message.ToString();
                NotificationLabel.Text = ex.Message.ToString();
            }

        }

        /// <summary>
        /// A operação de Reatamento limpa os dados da suspensão, incrementa a sequência de autorização em uma unidade,
        /// atribui a data do dia à textBox data de reatamento, mostra o número da nova autorização, muda o status da cobrança 
        /// para "First - primeira cobrança", bloqueia a combo de alterações de cobrança e muda a DropDownList 
        /// "Tipo de contribuição" para "DM"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ReatamentoBtn_Click(object sender, EventArgs e)
        {
            TextBox txt;
            DropDownList Ddl;

            int idSupporter = int.Parse(Request.QueryString["Id"]);

            ((DropDownList)FVAssociates.FindControl("BankCollectingTypesDdl")).SelectedValue = K_FIRST_COLLECTION.ToString();

            Ddl = FVAssociates.FindControl("ColletionAmendmentDdl") as DropDownList;
            Ddl.SelectedValue = K_AMENDMENT_NONE.ToString();
            Ddl.Enabled = false;

            ((DropDownList)FVAssociates.FindControl("DonationSituationDdl")).SelectedValue = K_DONATION_SITUATION_DM.ToString();

            ((TextBox)FVAssociates.FindControl("SuspensionDateTbox")).Text = string.Empty;

            ((DropDownList)FVAssociates.FindControl("SuspensionContatTypeDdl")).SelectedValue = string.Empty;

            ((DropDownList)FVAssociates.FindControl("ReasonSuspDdl")).SelectedValue = string.Empty;

            ((TextBox)FVAssociates.FindControl("ResumingDateTbox")).Text = DateTime.Today.ToString();

            txt = FVAssociates.FindControl("SequenceTbox") as TextBox;
            int seq = int.Parse(txt.Text);
            seq++;
            txt.Text = seq.ToString();

            ((TextBox)FVAssociates.FindControl("ResumingNewSequenceTbox")).Text = Generic.Instance.getResumenSequence(idSupporter, seq.ToString());

            txt = FVAssociates.FindControl("NumberBankTbox") as TextBox;
            txt.Focus();
        }

        /// <summary>
        /// Função auxiliar para validar o IBAN/NIB
        /// </summary>
        /// <returns></returns>
        private bool isValidIBAN()
        {
            string iban;
            TextBox txt;

            txt = (TextBox)FVAssociates.FindControl("CountryBankTbox");

            if (txt.Text.Trim() == string.Empty)
                iban = Iban.K_IBAN_PT;
            else
                iban = txt.Text.Trim();

            iban += ((TextBox)FVAssociates.FindControl("NumberBankTbox")).Text.Trim() +
                    ((TextBox)FVAssociates.FindControl("NumberAgencyTbox")).Text.Trim() +
                    ((TextBox)FVAssociates.FindControl("NumberAccountTbox")).Text.Trim() +
                    ((TextBox)FVAssociates.FindControl("CheckDigitAccountTbox")).Text.Trim();

            return Iban.Instance.isIBAN(iban);
        }

        /// <summary> 
        /// Valida o IBAN
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CheckIBANBtn_Click(object sender, EventArgs e)
        {
            //Label lbl = FVAssociates.FindControl("NotificationLabel") as Label;
            NotificationLabel.Visible = false;
            //lbl.Visible = false;

            if (!isValidIBAN())
            {
                NotificationLabel.Text = "IBAN/NIB inválido!";
                NotificationLabel.BackColor = Color.Red;
                NotificationLabel.Visible = true;
                //lbl.Text = "IBAN/NIB inválido!";
                //lbl.BackColor = Color.Red;
                //lbl.Visible = true;
            }
            else
            {
                NotificationLabel.Text = "IBAN/NIB Ok!";
                NotificationLabel.BackColor = Color.Green;
                NotificationLabel.Visible = true;
                //lbl.Text = "IBAN/NIB Ok!";
                //lbl.BackColor = Color.Green;
                //lbl.Visible = true;
            }
        }

        /// <summary>
        ///// A alteração do número de Banco provoca a mudança do status de cobrança para "First" e 
        ///// uma alteração da cobrança para "alteração de Banco"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void NumberBankTbox_TextChanged(object sender, EventArgs e)
        {
            ((DropDownList)FVAssociates.FindControl("BankCollectingTypesDdl")).SelectedValue = K_FIRST_COLLECTION.ToString();
            ((DropDownList)FVAssociates.FindControl("ColletionAmendmentDdl")).SelectedValue = K_AMENDMENT_CHG_BNK.ToString();
        }

        /// <summary>
        ///// A alteração do NIB apenas provoca uma alteração da cobrança para "Alteração de conta bancária (dentro do mesmo banco)"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void NumberAgencyTbox_TextChanged(object sender, EventArgs e)
        {
            if (((DropDownList)FVAssociates.FindControl("ColletionAmendmentDdl")).SelectedValue != K_AMENDMENT_CHG_BNK.ToString() &&
                ((DropDownList)FVAssociates.FindControl("ColletionAmendmentDdl")).SelectedValue != K_AMENDMENT_CHG_BNK_AUTH.ToString())

                ((DropDownList)FVAssociates.FindControl("ColletionAmendmentDdl")).SelectedValue = K_AMENDMENT_CHG_ACC.ToString();
        }
        
        /// <summary>
        /// Quando se altera a sequência da autorização é criada uma nova autorização, que é mostrada na TextBox ResumingSequenceTbox
        /// Essa informação só será guardada se for pressionado o botão "Gravar"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SequenceTbox_TextChanged(object sender, EventArgs e)
        {
            int idSupporter = int.Parse(Request.QueryString["Id"]);
            string sequence = ((TextBox)FVAssociates.FindControl("SequenceTbox")).Text.Trim();

            if (sequence != string.Empty)
            {
                ((TextBox)FVAssociates.FindControl("ResumingNewSequenceTbox")).Text = Generic.Instance.getResumenSequence(idSupporter, sequence);
                ((TextBox)FVAssociates.FindControl("ResumingDateTbox")).Focus();
            }
        }

        //protected override void InitializeCulture()
        //{
        //    UICulture = "pt-PT";
        //    Culture = "pt-PT";
        //}
    }
}